import { getUserInfo, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 路由表
}
const mutations = {
  setToken(state, token) {
    // 将token存储到vuex中 (vuex的数据在内存中, 刷新会丢失)
    state.token = token
    // 将token存储到cookie缓存中
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    // newRoutes 动态路由
    state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
  async login(context, payload) {
    // 1. 发送登录请求
    // 2. 获取token
    const data = await login(payload)
    // 3. 提交mutation
    context.commit('setToken', data)
  },
  async getUserInfo(context) {
    // 发请求 -> 获取用户信息
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('removeToken') // 删token
    context.commit('setUserInfo', {}) // 清除用户信息
    resetRouter() // 重置路由
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
